﻿using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Text;

namespace Core.Framework.Model.Common
{
    /// <summary>
    /// 注册服务商
    /// </summary>
    public class BuildServiceProvider
    {

        public static IServiceCollection ServiceCollection { get; } = new ServiceCollection();

        public static IServiceProvider ServiceProvider { get; set; }

        static IServiceProvider _Provider { get; set; }

        static object ProviderLock { get; set; } = new object();

        private static IServiceProvider serviceProvider
        {
            get
            {
                if (_Provider == null)
                {
                    lock (ProviderLock)
                    {
                        if (_Provider == null)
                        {
                            _Provider = ServiceCollection
                                .BuildServiceProvider();
                        }
                    }

                }

                return _Provider;
            }
            set
            {
                _Provider = value;
            }
        }

        /// <summary>
        /// 获取服务
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="model"></param>
        /// <returns></returns>
        public static T GetService<T>() where T : class
        {

            var provider = serviceProvider.GetService<T>();

            if (provider == null)
            {
                return ServiceProvider.GetService<T>();
            }

            return provider;
        }
    }

    public static class BuildServiceProviderExtent
    {
        /// <summary>
        /// 注册服务实例
        /// </summary>
        /// <param name="app"></param>
        /// <returns></returns>
        public static IApplicationBuilder RegisterServiceProvider(this IApplicationBuilder app)
        {
            BuildServiceProvider.ServiceProvider = app.ApplicationServices;
            return app;
        }
    }
}
